/*************************************************************************
	> File Name: HttpServer.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/24 15:52
 ************************************************************************/

#pragma once

#include "Sock.hpp"
#include <functional>

using fun_t = std::function<void(Sock*)>;

class HttpServer
{
public:
    HttpServer (const uint16_t& port, fun_t func, const std::string& ip = "0.0.0.0"):_sock(new Sock(port, ip)), _func(func)
    {
        if (!_sock->Bind()) {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(1);
        }
        if (!_sock->Listen()) {
            logMessage(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "init success");
    }

    void Start()
    {
        std::string input;
        Sock* sock = (Sock*)new AcSock(*_sock);
        while (1) {
            _func(sock);
        }
    }

private:
    Sock* _sock;
    fun_t _func;
};
